import path from 'path';
import fs from 'fs';
import { getUserDataPath } from '../utils/getUserDataPath';

class ConfigManager {
  config: any;

  constructor() {
    this.config = undefined;
  }

  async setup() {
    const _config = this.gather();
    this.config = _config;
    this.setLocal(_config);
  }

  get() {
    if (this.config) {
      return this.config;
    }
    const errMsg = '配置文件不存在';
    throw new Error(errMsg);
  }

  updateEnv(value) {
    const local = this.getEnvConfig();
    const _config = { ...local, ...value };
    this.setEnvConfig(_config);
    return _config;
  }

  getLocal() {
    let globalConfig;
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      const configFilePath = path.resolve(userDataPath, 'global.json');
      if (fs.existsSync(configFilePath)) {
        try {
          const raw = fs.readFileSync(configFilePath, { encoding: 'utf8' });
          const parsed = JSON.parse(raw);
          // 处理如果读到的是 HTML 字符串的情况
          if (typeof parsed === 'string') {
            throw new Error(
              'Parsed result is not JSON. Perhaps it parsed a HTML string'
            );
          }
          globalConfig = parsed;
        } catch {}
      }
    }
    return globalConfig;
  }

  setLocal(data) {
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      if (!fs.existsSync(userDataPath)) {
        // 不存在则创建文件夹
        fs.mkdirSync(userDataPath, { recursive: true });
      } else {
        const configFilePath = path.resolve(userDataPath, 'global.json');
        const content = JSON.stringify(data, null, 2);
        try {
          console.log('写入配置成功');
          fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
        } catch {
          console.log('写入配置失败');
        }
      }
    }
  }

  updateConfig(value) {
    const local = this.getLocal();
    const _config = { ...local, ...value };
    this.setLocal(_config);
    return _config;
  }

  getEnvConfig() {
    let configEnv;
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      const configFilePath = path.resolve(userDataPath, 'env.json');
      if (fs.existsSync(configFilePath)) {
        try {
          configEnv = JSON.parse(
            fs.readFileSync(configFilePath, { encoding: 'utf8' })
          );
        } catch (err) {}
      }
    }
    return configEnv;
  }

  setEnvConfig(data: any) {
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      if (!fs.existsSync(userDataPath)) {
        // 不存在则创建文件夹
        fs.mkdirSync(userDataPath, { recursive: true });
      } else {
        const configFilePath = path.resolve(userDataPath, 'env.json');
        const content = JSON.stringify(data, null, 2);
        try {
          fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
        } catch {
          console.log('写入配置失败');
        }
      }
    }
  }

  getUpTaskConfig() {
    let configEnv;
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      const configFilePath = path.resolve(userDataPath, 'uptask.json');
      if (fs.existsSync(configFilePath)) {
        try {
          configEnv = JSON.parse(
            fs.readFileSync(configFilePath, { encoding: 'utf8' })
          );
        } catch (err) {}
      }
    }
    return configEnv;
  }

  setUpTaskConfig(data: any) {
    const userDataPath = getUserDataPath();
    if (userDataPath) {
      if (!fs.existsSync(userDataPath)) {
        // 不存在则创建文件夹
        fs.mkdirSync(userDataPath, { recursive: true });
      } else {
        const configFilePath = path.resolve(userDataPath, 'uptask.json');
        const content = JSON.stringify(data, null, 2);
        try {
          fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
        } catch {
          console.log('写入配置失败');
        }
      }
    }
  }

  updateUpTaskConfig(value) {
    const local = this.getUpTaskConfig();
    const _config = { ...local, ...value };
    this.setUpTaskConfig(_config);
    return _config;
  }

  gather() {
    const localConfig = this.getLocal();
    if (localConfig) {
      return localConfig;
    }
    return {};
  }
}

export default new ConfigManager();
